import { requestTimeout, apiBaseUrl } from '../settings'
import { storage } from './storage'

export const http = ({
  method = 'GET',
  url = '',
  data = {},
  dataType = 'json',
}) => {
  const header = {}
  if (storage.get('token')) {
    // 刷新一遍缓存里的token
    storage.set('token', storage.get('token'))
    header['Authorization'] = `Bearer ${storage.get('token')}`
  } else {
    // 跳到登录
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${apiBaseUrl}${url}`,
      header,
      timeout: requestTimeout,
      data,
      method: method.toUpperCase(),
      success({ data, statusCode }) {
        // 如果statusCode 不是200，使用toast显示
        resolve(data)
      },
      fail(err) {
        reject(err)
      },
    })
  })
}

export const uploadImage = (url, imgFiles) => {
  const header = {}
  if (storage.get('token')) {
    // 刷新一遍缓存里的token
    storage.set('token', storage.get('token'))
    header['Authorization'] = `Bearer ${storage.get('token')}`
  } else {
    // 跳到登录
  }
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${apiBaseUrl}${url}`,
      header,
      filePath: imgFiles,
      name: 'file',
      success: res => {
        resolve(res)
      },
      fail: () => {
        reject(err)
      },
    })
  })
}
